import React, { useState, useContext, useRef, useEffect } from "react";
import { makeStyles } from "@material-ui/core/styles";
import { Divider, TextareaAutosize, Snackbar } from "@material-ui/core";
import { ArrowForward } from "@material-ui/icons";
import { queryContext } from "../contexts/QueryContext";

const DAYS = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"];
const QA = (props) => {
  const textArea = useRef(null);
  const resultContainer = useRef(null);
  const [time, setTime] = useState("");
  const [qaList, setQaList] = useState([
    {
      type: "answer",
      text:
        "该 AI 问答系统包含1亿条问答数据，其中有33万条银行业务问答。在下方对话框中输入问题，你的金融管家小M将会给出回答。（Demo 仅支持中文问答）",
    },
  ]);

  const [open, setOpen] = useState(false);
  const [message, setMessage] = useState("");
  const isMobile = props.isMobile;
  const { search } = useContext(queryContext);
  const { setLoading, loading } = props;

  const useStyles = makeStyles({
    wrapper: {
      display: "flex",
      width: "100%",
      flex: 1,
      flexDirection: "column",
    },
    content: {
      height: "calc(100vh - 8rem - 340px)",
      overflowY: "auto",
      color: "#000",
      padding: isMobile ? "20px" : "40px",
      fontSize: isMobile ? "12px" : "15px",
    },
    textarea: {
      position: "relative",
      flex: "0 0 154px",
      padding: "20px",
      backgroundColor: "#fff",
      borderTop: "1px solid #B0B0B9",
    },
    item: {
      display: "flex",
      marginTop: "16px",
    },
    avatar: {
      width: "60px",
      height: "60px",
      borderRadius: "50%",
      backgroundSize: "64px",
      backgroundImage: `url(
        ""
      )`,
    },
    text: {
      position: "relative",
      display: "flex",
      marginLeft: "20px",
      alignItems: "center",
      backgroundColor: "#fff",
      padding: "14px 21px",
      maxWidth: "300px",
      lineHeight: 1.6,
      color: "#000",
      borderRadius: "10px",
      ".question &": {
        backgroundColor: "#C7EDFF",
      },
      ".answer &": {
        backgroundColor: "#E5E5E5",
      },
      "& p": {
        maxWidth: "100%",
        wordBreak: "break-all",
      },
    },
    send: {
      position: "absolute",
      bottom: "20px",
      right: "30px",
      height: "60px",
      width: "60px",
      display: "flex",
      alignItems: "center",
      justifyContent: "center",

      color: "#B0B0B9",
      cursor: "pointer",
    },
    triangle: {
      position: "absolute",
      top: "16px",
      width: 0,
      height: 0,
      borderTop: "10px solid transparent",
      borderBottom: "10px solid transparent",
      ".question &": {
        borderLeft: "10px solid #AEE5FF",
      },
      ".answer &": {
        borderRight: "10px solid #fff",
      },
    },
  });
  const classes = useStyles({});

  const handleSend = (e) => {
    const value = textArea.current.value;
    if (!value.trim()) {
      setMessage("请输入问题");
      setOpen(true);

      setTimeout(() => {
        setOpen(false);
      }, 800);
      return;
    }
    setLoading(true);
    setQaList((list) => {
      let text = textArea.current.value;
      textArea.current.value = "";
      return [...list, { type: "question", text }];
    });
    search({ query_text: value }).then((res) => {
      const { status, data } = res || {};
      if (status === 200) {
        setQaList((list) => {
          return [...list, { type: "answer", text: data }];
        });
        setLoading(false);
      }
    });
  };

  useEffect(() => {
    const getTime = () => {
      const now = new Date();
      const year = now.getFullYear();
      const month = now.getMonth() + 1;
      const day = now.getDay();
      const date = now.getDate();
      const hour = now.getHours();
      const minutes = now.getMinutes();
      const seconds = now.getSeconds();
      return `${year}年${month}月${date}日 ${DAYS[day]} ${hour}:${minutes}:${seconds}`;
    };
    setTime(getTime());
  }, []);

  useEffect(() => {
    resultContainer.current.scrollTop = 10000;
  }, [qaList]);

  const handleKeyDown = (e) => {
    console.log(e.keyCode);
    if (e.keyCode === 13) {
      handleSend();
      e.preventDefault();
    }
  };

  return (
    <div className={classes.wrapper}>
      <div ref={resultContainer} className={classes.content}>
        {/* <p>该 AI 问答系统包含12万条医疗相关的问答。</p>
        <p> 在下方对话框中输入问题，你的健康管家小M将会给出回答。</p> */}
        {/* <p style={{ color: "#B0B0B9" }}>（Demo 仅支持中文问答）</p> */}
        <p style={{ textAlign: "center" }}>{time}</p>
        {qaList.map((v, i) => {
          if (v.type === "answer") {
            return (
              <div className={`${classes.item} answer`} key={i}>
                <div className={classes.avatar}></div>
                <div className={classes.text}>
                  <div
                    className={`${classes.triangle}`}
                    style={{ left: "-10px" }}
                  ></div>
                  <p>{v.text}</p>
                </div>
              </div>
            );
          } else {
            return (
              <div
                className={`${classes.item} question`}
                style={{ flexDirection: "row-reverse" }}
                key={i}
              >
                {/* <AccountCircleIcon style={{ fontSize: 50 }} /> */}
                <div className={classes.text} style={{ margin: "0 20px 0 0" }}>
                  {/* <div
                    className={classes.triangle}
                    style={{ right: "-10px" }}
                  ></div> */}
                  <p>{v.text}</p>
                </div>
              </div>
            );
          }
        })}
        {loading && (
          <div style={{ textAlign: "center", marginTop: "10px" }}>
            正在查询相关问题,请稍后...
          </div>
        )}
      </div>
      <Divider
        variant="middle"
        style={{ backgroundColor: "#fff", margin: " 0" }}
      />
      <div className={classes.textarea}>
        <TextareaAutosize
          ref={textArea}
          aria-label="empty textarea"
          placeholder="请输入问题，比如：银行面签后，公积金贷款多久能下来"
          rows={10}
          style={{
            width: "100%",
            boxSizing: "border-box",
            border: "none",
            color: "#000",
          }}
          onKeyDown={handleKeyDown}
        />
        <div className={classes.send}>
          <ArrowForward fontSize="large" onClick={handleSend}></ArrowForward>
        </div>
      </div>
      <Snackbar
        anchorOrigin={{ vertical: "top", horizontal: "center" }}
        key="top center"
        open={open}
        message={message}
      />
    </div>
  );
};

export default QA;
